package com.nageoffer.shortlink.project.utils;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.nageoffer.shortlink.common.constant.ShortLinkConstant;
import jakarta.servlet.http.HttpServletRequest;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.net.URI;
import java.util.Date;
import java.util.Optional;

public class LinkUtil {
    public static String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("X-Forwarded-For");

        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        }

        return ipAddress;
    }


    public static String getFaviconUrl(String url) throws IOException {
        // 发送 HTTP 请求并获取网页内容
        Document document = Jsoup.connect(url).get();

        // 查找 <link rel="icon"> 或 <link rel="shortcut icon"> 标签
        Element faviconElement = document.select("link[rel~=(?i)^(shortcut|icon|shortcut icon)$]").first();

        if (faviconElement != null) {
            // 获取图标的 href 属性
            String faviconHref = faviconElement.attr("href");

            // 处理相对路径
            if (!faviconHref.startsWith("http")) {
                // 构建完整的图标 URL
                return resolveRelativeUrl(url, faviconHref);
            }
            return faviconHref;
        }

        // 如果网页中没有指定图标，尝试访问默认的 /favicon.ico
        return resolveRelativeUrl(url, "/favicon.ico");
    }

    private static String resolveRelativeUrl(String baseUrl, String relativePath) {
        if (relativePath.startsWith("/")) {
            // 如果相对路径以 / 开头，直接拼接到域名后面
            return baseUrl.replaceFirst("(https?://[^/]+).*", "$1") + relativePath;
        } else {
            // 否则，拼接到基础路径后面
            return baseUrl.replaceAll("/[^/]*$", "/") + relativePath;
        }
    }
    public static long linkValidDateConvert(Date validDate){
        return Optional.ofNullable(validDate)
                .map(each-> DateUtil.between(new Date(),validDate, DateUnit.MS))
                .orElse(ShortLinkConstant.REDIS_CACHE_VALID_TIME);
    }
    public static String getOs(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("windows")) {
            return "Windows";
        } else if (userAgent.toLowerCase().contains("mac")) {
            return "Mac OS";
        } else if (userAgent.toLowerCase().contains("linux")) {
            return "Linux";
        } else if (userAgent.toLowerCase().contains("android")) {
            return "Android";
        } else if (userAgent.toLowerCase().contains("iphone") || userAgent.toLowerCase().contains("ipad")) {
            return "iOS";
        } else {
            return "Unknown";
        }
    }
    public static String getBrowser(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("edg")) {
            return "Microsoft Edge";
        } else if (userAgent.toLowerCase().contains("chrome")) {
            return "Google Chrome";
        } else if (userAgent.toLowerCase().contains("firefox")) {
            return "Mozilla Firefox";
        } else if (userAgent.toLowerCase().contains("safari")) {
            return "Apple Safari";
        } else if (userAgent.toLowerCase().contains("opera")) {
            return "Opera";
        } else if (userAgent.toLowerCase().contains("msie") || userAgent.toLowerCase().contains("trident")) {
            return "Internet Explorer";
        } else {
            return "Unknown";
        }
    }
    public static String getDevice(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        if (userAgent.toLowerCase().contains("mobile")) {
            return "Mobile";
        }
        return "PC";
    }
    public static String getNetwork(HttpServletRequest request) {
        String actualIp = getIp(request);
        // 这里简单判断IP地址范围，您可能需要更复杂的逻辑
        // 例如，通过调用IP地址库或调用第三方服务来判断网络类型
        return actualIp.startsWith("192.168.") || actualIp.startsWith("10.") ? "WIFI" : "Mobile";
    }
    public static String extractDomain(String url) {
        String domain = null;
        try {
            URI uri = new URI(url);
            String host = uri.getHost();
            if (StrUtil.isNotBlank(host)) {
                domain = host;
                if (domain.startsWith("www.")) {
                    domain = host.substring(4);
                }
            }
        } catch (Exception ignored) {
        }
        return domain;
    }

}
